package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Goal;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class GoalDao {
	private DBHelp<Goal> db = new DBHelp<Goal>();
	public void save(Goal goal) {
		String sql ="insert into t_goal(id,`name`,`desc`,employeeid,projectid)values(?,?,?,?,?)";
		db.executeSQL(sql,goal.getId(),goal.getName(),goal.getDesc(),goal.getEmployeeid(),goal.getProjectid());
	}
	public int count(String employeeid,String projectid) {
		String sql = "select count(*) from t_goal where employeeid = ? and projectid=?";
		return  db.executeQueryToNumber(sql,employeeid,projectid).intValue();
	}
	public Page<Goal> findByPageAndEmployeeIdAndProjectId(int pageNum,String employeeid, String projectid) {
		Page<Goal> page = new Page<Goal>(count(employeeid,projectid), pageNum);
		
		String sql ="select id,`name`,`desc`,createtime,`rate`,employeeid,projectid from t_goal  where employeeid = ? and projectid = ? order by createtime desc limit ?,?";
		List<Goal> list = db.executeQueryToList(sql,
		new RowMapper<Goal>() {
			public Goal mapRow(ResultSet rs) throws SQLException {
				Goal goal = new Goal();
				goal.setId(rs.getString("id"));
				goal.setName(rs.getString("name"));
				goal.setDesc(rs.getString("desc"));
				goal.setCreatetime(rs.getString("createtime"));
				goal.setRate(rs.getDouble("rate"));
				goal.setEmployeeid(rs.getString("employeeid"));
				goal.setProjectid(rs.getString("projectid"));
				return goal;
			}},
		employeeid,projectid,page.getStart(),page.getPageSize());
		
		page.setList(list);
		return page;
		

	}
	private class GoalRowMapper implements RowMapper<Goal> {

		public Goal mapRow(ResultSet rs) throws SQLException {
			Goal goal = new Goal();
			goal.setId(rs.getString("id"));
			goal.setName(rs.getString("name"));
			goal.setDesc(rs.getString("desc"));
			goal.setCreatetime(rs.getString("createtime"));
			goal.setRate(rs.getDouble("rate"));
			goal.setEmployeeid(rs.getString("employeeid"));
			goal.setProjectid(rs.getString("projectid"));
			
			return goal;
		}
		
	}
	public Goal findById(String id) {
		String sql ="select id,`name`,`desc`,createtime,rate,employeeid,projectid from t_goal where id = ?";
		return db.executeQueryToObject(sql, new GoalRowMapper(), id);
	}
	public void update(Goal goal) {
		String sql ="update t_goal set `name` =? , `desc`=? WHERE id= ?";
		db.executeSQL(sql, goal.getName(),goal.getDesc(),goal.getId());
	}
	public void delGoalById(String id) {
		String sql = "delete from t_goal where id = ?";
		db.executeSQL(sql, id);
	}
}
